require("../index.scss");
require("../addContract/index.scss");
var STip = ZFT.Util.STip;
var Ajax = ZFT.Util.Ajax;
var ParseTemplate = ZFT.Util.ParseTemplate;
var Pagination = require("COMMON/modules/pagination-x/v1.0/");
var ImgUploador = require("../../mem");
var Template = {
    resultList: ParseTemplate(require("./tpl/resultList.xtpl")),
    leasemodal: ParseTemplate(require("./tpl/leaseModal.xtpl")),
    feeTr: ParseTemplate(require("../tpl/feelist_tr_add.xtpl")),
    addleaseimg: ParseTemplate(require("../tpl/addleaseimg.xtpl")),
    growthrateinp: ParseTemplate(require("../tpl/growthratebinp.xtpl")),
    billmodal: ParseTemplate(require("./tpl/billModal.xtpl"))
}
var Main = ZFT.Util.Class({
    container: $("body"),
    EVENTS: {
        "click .cancel.m,.close.m": "closeModal",
        "click .del-btn": "onClickImgDivDelbtn"
    },
    init: function () {
        var _this = this;
        //初始化分页
        var pagination = this.pagination = new Pagination({
            container: $(".paginationWrap"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        })
        pagination.on("page.switch", function (toPage, currentPage, totalPage) {
            pagination.render({ current: currentPage, toPage: toPage }),
                _this.getResultList(toPage);
        });
        _this.getResultList(1)
        _this.bindClickEvent();
    },
    bindClickEvent: function () {
        var _this = this;
        $("#getResultBtn").on("click", function (e) {
            _this.getResultList(1);
        });

    },
    getResultList: function (toPage) {
        if (!toPage) toPage = 1;
        var _this = this;
        var pagination = $(".paginationWrap");
        var pageSize = pagination.attr("data-size");
        var tbody = $("#tbody");
        var param = {
            name: $("#buildingName").val(),
            room: $("#room").val(),
            page: toPage,
            page_size: pageSize ? pageSize : 10
        }
        Ajax("/r/Lease_getImportOrder", {
            type: "POST",
            dataType: "json",
            params: param,
            loading: function () {
                pagination.hide();
                var loading = '<tr><td colspan="5">正在加载,请稍后...</td></tr>'
                tbody.html(loading);
            },
            success: function (res) {
                if (res.code == 200) {
                    var data = res.data;
                    /*var dataa=[{
                        bname:"aaa",
                        room:"1234",
                        name:"xxxxxx",
                        tel:"15259118313",
                        id:"123"
                    },{
                        bname:"aaaasda",
                        room:"1232434",
                        name:"福建福州x",
                        tel:"15259118314",
                        id:"1233"
                    }]*/
                    var resultList;

                    var pers = ZFT.Util.getPermission(),
                        btnPer;
                    btnPer = ($.inArray("30", pers) !== -1) ? 1 : 0
                    data["btnPer"] = btnPer;
                    resultList = Template.resultList({ data: data });
                    tbody.html(resultList);
                    _this.openLeaseFixModal();
                    _this.pagination.render({ current: toPage, toPage: toPage, total: /*data.total*/1 })

                } else {
                    tbody.html('<tr><td colspan="5">' + res.msg + '</td></tr>')
                }
            }
        })
    },
    //打开合同详情模态框
    openLeaseFixModal: function () {
        var _this = this;
        $("#tbody .btn-fix").on("click", function (e) {
            var tarBtn = $(e.currentTarget),
                ordernum = tarBtn.attr("data-num"),
                house_number = tarBtn.attr("data-no"),
                build_id = tarBtn.attr("data-id"),
                param = {
                    ordernum: ordernum
                },
                info_data = _this.getLeaseInfo(house_number, build_id);
                _this.getLeasDetail(param, info_data, house_number);

        })
    },
    //获取详情
    getLeasDetail: function (param, info_data, house_number) {
        var _this = this;
        Ajax("/r/Lease_importOrderDetail", {
            type: "POST",
            dataType: "json",
            params: param,
            success: function (res) {
                if (res.code == 200) {
                    var modal,
                        data = res.data;
                    data["data"] = info_data.responseJSON.data;
                    modal = Template.leasemodal({ data: data });
                    $("#modal").html(modal);
                    _this.initDatepicker();
                    _this.checkFeeObj();
                    _this.listenInp();
                    _this.checkDate(data);
                    _this.creatFeeList(data.ordernum, house_number);
                    _this.initImgUpload("i1"); //初始化图片上传
                    _this.initImgUpload("i2");
                    _this.initImgUpload("1");
                    _this.clickAddImgDiv();
                    _this.checkTaxToEnableTaxInp();
                } else {
                    return STip("fail", res.msg);
                }
            }
        })

    },
    //获取数据
    getLeaseInfo: function (house_number, build_id) {
        var arr = [];
        arr.push(house_number)
        return data = $.ajax({
            url:"/r/Lease_findHouseInfo",
            type: "POST",
            dataType: "json",
            async:false,
            data: {
                houseId: JSON.stringify(arr),
                building_id: build_id
            },
            success: function (res) {
                if (res.code != 200) {
                    return STip("fail", res.msg);
                }
            }
        })
    },
    //检测租赁时间间隔
    checkDate: function (data) {
        var _this = this,
            beginDate = data.begin_time + "",
            endDate = data.end_time + "",
            by = beginDate.substr(0, 4),
            bm = beginDate.substr(4, 2),
            bd = beginDate.substr(6, 2),
            ey = endDate.substr(0, 4),
            em = endDate.substr(4, 2),
            ed = endDate.substr(6, 2),
            newBeginDate = by + "/" + bm + "/" + bd,
            newEndDate = ey + "/" + em + "/" + ed,
            // freeDay = $("#freeDay").val(),
            fmBeginDate = new Date(newBeginDate).getTime() / 1000,
            fmEndDate = new Date(newEndDate).getTime() / 1000,
            newFmBeginDate = new Date((fmBeginDate) * 1000),
            newFmEndDate = new Date((fmEndDate) * 1000),
            beginY = newFmBeginDate.getFullYear(),
            endY = newFmEndDate.getFullYear(),
            beginM = newFmBeginDate.getMonth() + 1,
            endM = newFmEndDate.getMonth() + 1,
            beginD = newFmBeginDate.getDate(),
            endD = newFmEndDate.getDate(),
            compareY = endY - beginY;

        if (!beginDate || !endDate) return false;
        if (fmBeginDate > fmEndDate) {
            tarInp.val("");
            return STip("fail", "退租时间不能早于起租时间!", 5000);
        }
        if (parseInt(fmEndDate) - parseInt(fmBeginDate) > 315532800) {
            //console.log(parseInt(endDate.replace(/-/g, '')) - parseInt(beginDate.replace(/-/g, '')))
            return STip("fail", "租赁时间不超过10年!", 5000);
        }
        if (newFmBeginDate < newFmEndDate) {
            if (beginM == endM) {
                if (beginD <= endD) {
                    _this.createGroRateBox(compareY + 1);
                } else {
                    _this.createGroRateBox(compareY);
                }
            } else if (beginM > endM) {
                _this.createGroRateBox(compareY);
            } else {
                _this.createGroRateBox(compareY + 1);
            }
        } else {
            _this.createGroRateBox(1);
        }
    },
    //生成增长率input框
    createGroRateBox: function (len) {
        var html;
        if (len - 1 < 0) return false;
        html = Template.growthrateinp({ data: len });
        $("#growthRateBox").html(html);
    },
    //选中收费对象的时候生成对应收费比例输入框
    checkFeeObj: function () {
        var _this = this;
        var feeObj = $("#tbody .feelabel");
        feeObj.on("change", ".feeObj", function (e) {
            var that = $(e.currentTarget);
            var dataId = that.attr("data-id"); // "收费对象 0 超管，1 业主， 2租户, 3托管公司, 4运营方, 5物业公司, 6水电公司"
            //  console.log(dataId)
            _this.creatRationInp(dataId, that);
        })

    },
    //生成收费比例输入框
    creatRationInp: function (dataId, target) {
        //console.log(dataId, target,target.prop("checked"));
        if (target.prop("checked")) {
            target.parents(".objTd").siblings(".ratioTd").find("input[data-id=" + dataId + "]").show();
        } else {
            target.parents(".objTd").siblings(".ratioTd").find("input[data-id=" + dataId + "]").hide().val('');
        }
    },
    //生成收费明细列表
    creatFeeList: function (ordernum, house_number) {
        var _this = this;
        var addBtn = $("#add");
        var addFeeList = $("#addFeeList");
        addBtn.off("click");
        // saveBtn.off("click");
        addBtn.on("click", function () {
            var feeChkBox = $("#tbody .feeTd input[type=checkbox]:checked");
            var feeInfo = [];
            if (feeChkBox.length < 1) return STip("fail", "请至少选中一个收费项目!");
            for (var i = 0, len = feeChkBox.length; i < len; i++) {
                var objChkBox = feeChkBox.eq(i).parent().siblings(".objTd").find(':checkbox:checked');
                var feeTr = feeChkBox.eq(i).parent().parent();
                var fee = feeTr.attr("data-money");
                var feeType = feeTr.attr("data-type");
                var ratioInp = feeChkBox.eq(i).parent().siblings(".ratioTd").find("input:visible");
                var ratio = 0;

                if (objChkBox.length < 1) return STip("fail", "请至少选择一个收费对象!");

                for (var j = 0, leng = ratioInp.length; j < leng; j++) {
                    var ratioInpVal = ratioInp.eq(j).val();
                    var feeObjCt = ratioInp.eq(j).attr("data-info"); //缴费对象账号
                    var feeObjId = ratioInp.eq(j).attr("data-id"); //缴费对象账号
                    if (!ratioInpVal) return STip("fail", "比例不能为空!")
                    ratio = ratio + parseInt(ratioInpVal);
                    feeInfo.push({ "fee": fee, "owner_id": feeObjCt, "type": feeType, "ratio": ratioInpVal, "objType": feeObjId });
                }
                if (parseInt(ratio) != 100) {
                    return STip("fail", "费用比例相加必须为100!");
                }
            }

            var html = Template.feeTr({ data: feeInfo });
            addFeeList.html(html);
            //预览或提交数据
            _this.viewBillOrSaveBill(feeInfo, ordernum, house_number);
        })

    },
    viewBillOrSaveBill: function (feeInfo, ordernum, house_number) {
        var _this = this;
        $("#viewBtn").on("click", function (e) {
            var photo = _this.formatImgSrcToString();
            var ztype = $("#ztype").val();
            var discount = $("#discountInp").val();
            //生成折扣率数组
            var rateArr = [];
            var regx = /^(\d*\.)?\d+$/;
            var regTime = /^\d+$/;
            var regTel = /^1\d{10}$/;
            var $rateInp = $("#growthRateBox .rateInp");
            //生成水电读数数组
            var meterArr = [];
            var $waterMeterInp = $("#meterList .water_meter");
            var $elecMeterInp = $("#meterList .electric_meter");
            var params;
            if (!regx.test($elecMeterInp.val())) return STip("fail", "请输入正确的电表读数，保留2位小数");
            if (!regx.test($waterMeterInp.val())) return STip("fail", "请输入正确的水表读数，保留2位小数");
            //水电抄表
            meterArr.push({ house_number: house_number, water: parseFloat($waterMeterInp.val()).toFixed(2), power: parseFloat($elecMeterInp.val()).toFixed(2) });
            //折扣率
            for (var i = 0; i < $rateInp.length; i++) {
                var $val = $rateInp.eq(i).val();
                rateArr.push(parseFloat($val).toFixed(2))
                //console.log($val);
            }
            params = {
                ordernum: ordernum,
                use_billing_day: ($("#isBillDay").is(":checked")) ? 1 : 0,
                contract_time: $("#contractTime").val(),
                id_card_a: $("#id_card_hand_hid_inp").val(),
                id_card_b: $("#id_card_B_hid_inp").val(),
                finance_user: $("#financeUser").val(),
                growth_rate: (rateArr.length > 0) ? JSON.stringify(rateArr) : "",
                house_number: house_number,
                meter: JSON.stringify(meterArr),
                feeInfo: JSON.stringify(feeInfo),
                photo: photo ? photo : "",
                legal_id_card: (ztype == 1) ? $("#legalIdCard").val() : "",
                type: "0",
                user_type: $("#ztype").val()
            }
            if ($("#ifTax").prop("checked") && tax) {
                var regxx = /^[0]+/;
                var taxx;
                if (regx.test(tax)) {
                    if (tax > 100) {
                        return STip("fail", "税点值在0~100之间!");
                    }
                } else {
                    return STip("fail", "税点值在0~100之间!");
                }
                params["tax"] = tax.replace(regxx, "");
            } else if ($("#ifTax").prop("checked") && !tax) {
                return STip("fail", "确定收税后,税点不为空!");
            }
            if (!regTime.test(params["contract_time"])) return STip("fail", "请选择签约时间！");
            if (!params["finance_user"]) return STip("fail", "财务联系人姓名不为空!");
            if (discount && regx.test(discount)) {
                if (regx > 10) return STip("fail", "房租折扣应在0.1~10之间!");
                params["discount"] = parseFloat(discount).toFixed(2);
            }
            if (!params["id_card_a"] || !params["id_card_b"]) return STip("fail", "身份证照片信息不全！");
            _this.viewOrSubmit(params);
        })

    },
    viewOrSubmit: function (params) {
        var _this = this;
        Ajax("/r/Lease_handleImportOrder", {
            type: "POST",
            dataType: "json",
            params: params,
            success: function (res) {
                if (res.code == 200) {
                    if (params.type == 0) {
                        var reg = /^(\d*\.)?\d+$/;
                        var billModal = Template.billmodal({ data: res.data });
                        $("#billModal").html(billModal);
                        $("#saveBtn").on("click", function (e) {
                            var arr = [];
                            var chkInp = $("#detailTbody .inp-billchk:checked");
                            if (chkInp.length < 1) return STip("fail", "请至少选择一个账单！");
                            for (var i = 0, len = chkInp.length, val, id; i < len; i++) {
                                id = chkInp.eq(i).attr("data-id");
                                val = chkInp.eq(i).parents(".u-box-date").siblings(".u-box-money").find(".u-inp_money").val();
                                console.log(reg.test(val), val)
                                if (!reg.test(val)) return STip("fail", "金额格式有误！");
                                arr.push({ id: id, fee: val });
                            }
                            params["type"] = 1;
                            params["bill_data"] = JSON.stringify(arr);
                            _this.viewOrSubmit(params);
                        })
                        $(".close.bill,.cancel.bill").on("click", function (e) {
                            $("#billModal").html("");
                        })
                    } else {
                        STip("success", res.msg);
                        $("#leaseModal").fadeOut(200);
                        _this.getResultList(1);
                    }
                } else {
                    return STip("fail", res.msg);
                }
            }
        })
    },
    //初始化日历插件
    initDatepicker: function () {
        $("#contractTime").datepicker({
            format: "yyyymmdd",
            maxViewMode: 2,
            language: "zh-CN",
            todayHighlight: true,
            autoclose: true
        });
        /*$('#endDate').datepicker({
            format: "yyyy-mm-dd",
            maxViewMode: 2,
            language: "zh-CN",
            autoclose: true
        });*/
    },
    //勾选是否收税来解除对应项目以及税点的只读
    checkTaxToEnableTaxInp: function () {
        var taxProj = "#taxProj";
        var tax = "#tax";
        $("#ifTax").on("change", function (e) {
            var $tar = $(e.currentTarget);
            if ($tar.prop("checked")) {
                $(taxProj + "," + tax).removeAttr("disabled", "disabled");
            } else {
                $(taxProj + "," + tax).attr("disabled", "disabled");
            }
        })
    },
    //监听input,输入的值只能为不大于100的整数
    listenInp: function () {

        $("#tbody input[type='text']").bind("input propertychange", function () {
            var $_this = $(this);
            var val = $_this.val();
            var exp = /^[0-9]\d*$/;
            if (exp.test(val)) {
                if (val > 100) {
                    $_this.val(100);
                    return false;
                } else if (val == 0 && val.length > 1) {
                    $_this.val(0);
                    return false;
                } else if (val.length > 1 && val.indexOf("0") == 0) {
                    var reg = /0/g;
                    var Val = val.replace(reg, "");
                    $_this.val(Val)
                }
            } else {
                $_this.val('');
                return false
            }

            //console.log(val)
        })
    },
    //初始化图片上传插件
    initImgUpload: function (i) {
        var uploadorname = $("#imgLoaderContainer_" + i).find("input[name=callback]").val();
        if (uploadorname) {
            uploadorname = uploadorname.split(".")[0];
            window[uploadorname] = new ImgUploador({ container: $("#imgLoaderContainer_" + i) });
        }
    },
    //点击图片添加按钮
    clickAddImgDiv: function (e) {
        var _this = this;
        var i = 1;
        var addImgDivId = "#addLeaseImgDiv";
        var addImgDiv;
        $(addImgDivId).on("click", function (e) {
            i++;
            var tarBtn = $(e.currentTarget);
            addImgDiv = Template.addleaseimg({ i: i });
            tarBtn.parents(".fbox.lt").before(addImgDiv);
            _this.initImgUpload(i);
        })
    },
    //删除当前图片上传的容器
    onClickImgDivDelbtn: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".lt").hide(200, function () {
            tarBtn.parents(".lt").remove();
        });
    },
    //遍历图片地址为字符串
    formatImgSrcToString: function () {
        var imgUrl;
        var array = [];
        $.each($("#leaseUploadBox  .hidInp_imgurl"), function (i, url) {
            if ($(url).val()) {
                array.push($(url).val());
            }
        })
        imgUrl = array.join(",");
        return imgUrl;
    },

    //关闭模态框
    closeModal: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".m-modal_bg").fadeOut(200);
    }
});

$(function () {
    new Main();
})